<template>
  <div v-if="visible">
    <el-dialog
      :model-value="showDialog" :close-on-press-escape="false" :close-on-click-modal="false"
      :show-close="false" title="添加用户">
      <el-table :highlight-current="true"
                :data="userList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="trueName" label="用户姓名"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="email" label="邮箱"/>
      </el-table>
      <template #footer>
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" @click="saveUserList">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { onBeforeMount, ref } from 'vue'
import { addUserDepartmentUrl, selectUserListNotInDeptIdUrl } from '@/api/api'
import { post } from '@/utils/httpRequest'

export default {
  name: 'userList',
  setup (props, { emit }) {
    const showDialog = ref(true)
    const cancel = () => {
      emit('update:visible', false)
    }
    const saveUserList = async () => {
      const result = await post(addUserDepartmentUrl, addUserListRequest.value)
      if (result.code === 200) {
        emit('save')
        emit('update:visible', false)
      }
    }
    const userList = ref([])
    const request = ref({
      pageNum: 1,
      pageSize: 10,
      deptId: 0
    })
    const addUserListRequest = ref({
      deptId: 0,
      ids: []
    })
    const handleSelectionChange = (rows) => {
      console.log(rows)
      addUserListRequest.value.ids = []
      rows.forEach(item => {
        addUserListRequest.value.ids.push(item.id)
      })
    }
    const selectUserListNotInDeptIdAsync = async () => {
      const result = await post(selectUserListNotInDeptIdUrl, request.value)
      if (result.code === 200) {
        userList.value = result.data.records
        console.error(userList.value)
      }
    }
    onBeforeMount(() => {
      request.value.deptId = props.deptId
      addUserListRequest.value.deptId = props.deptId
      selectUserListNotInDeptIdAsync()
    })
    return {
      saveUserList,
      handleSelectionChange,
      userList,
      selectUserListNotInDeptIdUrl,
      showDialog,
      cancel
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: false
    },
    // 部门id
    deptId: {
      type: Number,
      default: 0,
      required: true
    }
  }
}
</script>

<style scoped>

</style>
